package models

import (
	"gopkg.in/mgo.v2/bson"
	"iris_test/models"
	"regexp"
	"strings"
)

type SiteRedirect struct {
	models.Models
}

func (siteRedirect * SiteRedirect) Init() *SiteRedirect{
	siteRedirect.Dbname = "supsite"
	siteRedirect.Tbname = "site_redirect"
	siteRedirect.InitConn()
	return siteRedirect
}
/**
 * 获取下301跳转信息
 */
func (SiteRedirect *SiteRedirect)GetRedirectInfo(siteid, fromUrl string)string {
	res := SiteRedirect.FindOne(bson.M{
		"siteid":bson.ObjectIdHex(siteid),
		"type" : 1,
		"state" : 1,
	})
	if len(*res) == 0 {
		return ""
	}
	urldata := (*res)["urldata"]
	check := map[int]int{2:2, 3:3}
	for _, v := range(urldata.([]interface{})) {
		tmpData := strings.Split(v.(string), ";")
		if _, ok := check[len(tmpData)];!ok {
			continue
		}
		if strings.Trim(tmpData[0], "") == "" || strings.Trim(tmpData[1], "") == "" || tmpData[0] == tmpData[1]{
			continue
		}
		if tmpData[0] == fromUrl && len(tmpData) == 2 {
			return tmpData[1]
		}
		if tmpData[2] != "regexp" {
			continue
		}
		regexStr := ""
		if strings.Count(tmpData[0] , "") >= 3 {
			regexStr = tmpData[0][1:strings.Count(tmpData[0] , "") - 2]
		} else {
			regexStr = tmpData[0]
		}
		if match,_ := regexp.MatchString(regexStr, fromUrl); match {
			return tmpData[1]
		}
	}
	return ""
}